# -*- coding: utf-8 -*-
"""
启动和测试脚本
"""

import subprocess
import time
import requests
import sys
import os

def install_dependencies():
    """安装依赖"""
    print("📦 正在安装依赖...")
    try:
        subprocess.run([sys.executable, "-m", "pip", "install", "-r", "requirements.txt"], check=True)
        print("✅ 依赖安装完成")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ 依赖安装失败: {e}")
        return False

def start_server():
    """启动服务器"""
    print("🚀 正在启动服务器...")
    try:
        # 启动服务器进程
        process = subprocess.Popen([sys.executable, "main.py"], 
                                 stdout=subprocess.PIPE, 
                                 stderr=subprocess.PIPE)
        
        # 等待服务器启动
        time.sleep(3)
        
        # 检查服务器是否启动成功
        try:
            response = requests.get("http://127.0.0.1:8000/", timeout=5)
            if response.status_code == 200:
                print("✅ 服务器启动成功")
                return process
            else:
                print("❌ 服务器启动失败")
                process.terminate()
                return None
        except requests.exceptions.RequestException:
            print("❌ 无法连接到服务器")
            process.terminate()
            return None
            
    except Exception as e:
        print(f"❌ 启动服务器失败: {e}")
        return None

def test_api():
    """测试API"""
    print("\n🧪 开始测试API...")
    
    # 测试注册
    register_data = {
        "username": "testuser",
        "name": "测试用户",
        "email": "test@example.com",
        "password": "123456"
    }
    
    try:
        response = requests.post("http://127.0.0.1:8000/v1/UserRegister", json=register_data)
        print(f"注册测试 - 状态码: {response.status_code}")
        if response.status_code == 200:
            print("✅ 注册功能正常")
        else:
            print(f"❌ 注册失败: {response.json()}")
    except Exception as e:
        print(f"❌ 注册测试失败: {e}")
    
    # 测试登录
    login_data = {
        "username": "testuser",
        "password": "123456"
    }
    
    try:
        response = requests.post("http://127.0.0.1:8000/v1/UserLogin", json=login_data)
        print(f"登录测试 - 状态码: {response.status_code}")
        if response.status_code == 200:
            print("✅ 登录功能正常")
        else:
            print(f"❌ 登录失败: {response.json()}")
    except Exception as e:
        print(f"❌ 登录测试失败: {e}")

def main():
    """主函数"""
    print("🎯 FastAPI 用户认证系统启动和测试")
    print("=" * 50)
    
    # 检查依赖
    if not install_dependencies():
        print("请手动安装依赖: pip install -r requirements.txt")
        return
    
    # 启动服务器
    server_process = start_server()
    if not server_process:
        print("服务器启动失败，请检查配置")
        return
    
    try:
        # 测试API
        test_api()
        
        print("\n🎉 测试完成！")
        print("服务器正在运行，访问地址:")
        print("- API文档: http://127.0.0.1:8000/docs")
        print("- 根路径: http://127.0.0.1:8000/")
        print("\n按 Ctrl+C 停止服务器")
        
        # 保持服务器运行
        server_process.wait()
        
    except KeyboardInterrupt:
        print("\n🛑 正在停止服务器...")
        server_process.terminate()
        print("✅ 服务器已停止")

if __name__ == "__main__":
    main() 